const express = require('express');
const cors = require('cors');
const fs = require('fs').promises;
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static('public'));

// 数据文件路径
const dataPath = path.join(__dirname, '..', 'data', 'leaderboard.json');

// 确保数据文件存在
async function ensureDataFile() {
    try {
        await fs.access(dataPath);
    } catch {
        await fs.mkdir(path.dirname(dataPath), { recursive: true });
        await fs.writeFile(dataPath, JSON.stringify({}));
    }
}

// 获取排行榜
app.get('/api/leaderboard/:game', async (req, res) => {
    try {
        await ensureDataFile();
        const data = JSON.parse(await fs.readFile(dataPath, 'utf8'));
        const game = req.params.game;
        const leaderboard = data[game] || [];
        
        // 按得分降序排序，取前10名
        const top10 = leaderboard
            .sort((a, b) => b.score - a.score)
            .slice(0, 10);
            
        res.json(top10);
    } catch (error) {
        res.status(500).json({ error: '获取排行榜失败' });
    }
});

// 提交得分
app.post('/api/leaderboard/:game', async (req, res) => {
    try {
        await ensureDataFile();
        const data = JSON.parse(await fs.readFile(dataPath, 'utf8'));
        const game = req.params.game;
        const { name, score } = req.body;
        
        if (!name || !score) {
            return res.status(400).json({ error: '缺少必要参数' });
        }
        
        if (!data[game]) {
            data[game] = [];
        }
        
        data[game].push({ name, score, date: new Date().toISOString() });
        
        await fs.writeFile(dataPath, JSON.stringify(data, null, 2));
        
        res.json({ success: true });
    } catch (error) {
        res.status(500).json({ error: '提交得分失败' });
    }
});

app.listen(PORT, () => {
    console.log(`服务器运行在 http://localhost:${PORT}`);
});
